var eventObj = require("../event");
var fs = require("fs");
var _ = require("underscore");

function TramStatusJson(options){
    this.tramCode = options.tramCode || '101';
    this.serviceNum = options.serviceNum || null;
    this.runPlan = options.runPlan;
    this.lineCode;             //线路号
    this.latitude;             //纬度
    this.longtitude;           //经度
    this.direct;		     //上下行
    this.fromTerminus;         //上一站站台
    this.toTerminus;           //下一站站台
    this.distance = 0;			 //距前方车站的距离
    this.mileage = 0;             //里程
    this.speedLimit;          //限速值
    this.speed = 30;               //速度
    this.soonerOrLater;       //早晚点信息
    this.arrivingTime;           //到站时间
    this.faultStatus;          //错误信息
    this.driverCode = 3000;           //驾驶员编号
    this.isInline = true;     //是否在线
    this.isError = false;     //是否存在异常
    this.runPercent;          //已运行区间百分比
    this.lastDate;               //最近一次接收数据的时间
    this.Length ;         //电车长度
    this.end ;				 //是否停止服务
    this.tramIp;				 //车辆IP
    this.totalLength = options.totalLength||0;      //车辆总里程

    this.currentSegment;       //当前车头所在区段
    this.runDistance = 3;          //当前车头所在区段越过的距离
    this.status = "offline";

    //停车所需相关参数
    this.stopArgs = {
        isStop : false,
        waitTime : 0
    };
    this.packetNum = 0  //车辆发包序号
    this.runExecutor = options.runExecutor||null;
    this.avgSpeed = 30;
    this.isReached = false;
    this.sectionArr = [];
}

module.exports = TramStatusJson;

TramStatusJson.prototype.run = function(){
    //在大循环中只运行一次,配置基本参数
    var $this = this;
    $this.lineCode = 1;
    _.each($this.runPlan,function(ele,i){
        if($this.runExecutor.getSeconds(ele.startTime) <= $this.runExecutor.passTimeBySec && ($this.runExecutor.getSeconds(ele.endTime)) >= $this.runExecutor.passTimeBySec){
            $this.serviceNum = ele.serviceNum;
            $this.railDirectType = ele.direct;
            $this.direct = ele.direct;
            _.each(ele.sections,function(element){

                //在区段内处于运行状态
                if($this.runExecutor.getSeconds(element.startTime) <= $this.runExecutor.passTimeBySec && $this.runExecutor.getSeconds(element.arriveTime) > $this.runExecutor.passTimeBySec){
                    $this.move(element);
                    console.log(ele.tramCode+'+++++++++++++++++run');
                    //在区段内处于停止状态
                }else if( $this.runExecutor.getSeconds(element.arriveTime) <= $this.runExecutor.passTimeBySec && ($this.runExecutor.getSeconds(element.arriveTime)+element.stopTime) >= $this.runExecutor.passTimeBySec ){
                    console.log(ele.tramCode+'----------------stop');
                    $this.arriveStation(element);
                }else{
                    //.............................有待处理
                }
            });
            $this.runExecutor.runFlag = true;
        }
    });

}

TramStatusJson.prototype.move = function(data){
       var $this = this;
       $this.isReached = 0;
       var currentSection = $this.getSection(data.fromStation,data.toStation);
       $this.fromTerminus = currentSection.from_terminus;
       $this.toTerminus = currentSection.to_terminus;
        var arrivalTimeBySec = $this.runExecutor.getSeconds(data.arriveTime);
        var startTimeBySec = $this.runExecutor.getSeconds(data.startTime);
        $this.speed = Math.round(currentSection.Length/(arrivalTimeBySec - startTimeBySec )*3.6);
        $this.runPercent = parseInt(($this.runExecutor.passTimeBySec - startTimeBySec)/(arrivalTimeBySec - startTimeBySec)*100);
        $this.mileage = Math.round(currentSection.Length * $this.runPercent/100);
        $this.distance = currentSection.Length - $this.mileage;
      //  $this.currentSegment = $this.getCurrentSegment(currentSection.code,$this.distance);

        $this.soonerOrLater = 0;
        $this.totalDistance = 0;
}

/*停站等待*/
TramStatusJson.prototype.arriveStation = function(data){
    var $this = this;
    $this.isReached = 1;

    var currentSection = $this.getNextSection(data.fromStation,data.toStation);
    $this.fromTerminus = currentSection.from_terminus;
    $this.toTerminus = currentSection.to_terminus;
    $this.speed = 0;
    $this.runPercent = 100;
    $this.mileage = currentSection.Length;
    $this.distance = currentSection.Length;
  //  $this.currentSegment = $this.getCurrentSegment(currentSection.code,$this.distance);
    $this.soonerOrLater = 0;
    $this.totalDistance = 0;

}

//发送车载状态包
TramStatusJson.prototype.sendStatusEventInfo = function(){
    var $this = this;
    var tempobj = {
        "tramCode" : $this.tramCode,
       // "currentSegment" : $this.currentSegment,
        "direct" : $this.direct,
        "speed" : $this.speed,
        "lineCode" : $this.lineCode,
        "serviceNum" : $this.serviceNum,
        "distance": $this.distance,
        // "mileage" : $this.mileage,
        "fromTerminus" : $this.fromTerminus,
        "toTerminus" : $this.toTerminus,
        "driverNum" : $this.driverCode,
        "packetNum" : $this.packetNum,
        "totalLength" : $this.totalLength,
        "isReached": $this.isReached
    }
    console.log(tempobj);
    $this.packetNum ++;
    return tempobj;

}

TramStatusJson.prototype.createSectionArrData = function(){
    var $this = this;
    var sectionData = eval("(" + fs.readFileSync("./datas/section.json", "utf-8")+ ")");
    $this.sectionArr = sectionData.rows;
}

TramStatusJson.prototype.getSection = function(fromStation, toStation){
    var $this = this;
    var section = null;
    _.forEach($this.sectionArr,function(ele,index){

      if(ele.from_station===fromStation && ele.to_station ===toStation){
        section = ele;
      }
    })
    return section;
}

TramStatusJson.prototype.getNextSection = function(fromStation, toStation){
    var $this = this;
    //首末站是不需要寻找下一区间的
    if(fromStation === "13"||fromStation === "14"||toStation === "6"||toStation === "7"){
        return $this.getSection(fromStation,toStation);
    }
    //上行fromStation和toStation是递增的
    if($this.direct == "up"){
        return $this.getSection(String(parseInt(fromStation)+1),String(parseInt(toStation)+1));
    }else{
        return $this.getSection(String(parseInt(fromStation)-1),String(parseInt(toStation)-1));
    }
}

//根据游标获取当前segment
TramStatusJson.prototype.getSegment = function(index){
    var $this = this;
    if (_.isNaN(index)||index >= $this.segmentArr.length||index < 0) {
        return null;
    };
    var segmentCode = $this.segmentArr[index].itemCode;
    var currentSegment = $this.runExecutor.getSegmentStatusByCode(segmentCode);
    return currentSegment;

}

TramStatusJson.prototype.getCurrentSegment = function(sectionCode, distance){
    var $this = this;
    var $distance = distance;
    var findFlag = false;
    var currentSegment = null;
  //  console.log(sectionCode +"**********************************" + $distance);
    var tempArr = _.filter($this.runExecutor.route[0].routeItems,function(ele){
        return ele.sectionCode == sectionCode;
    })
    var sortedArr = _.sortBy( tempArr,function(ele){
        return -ele.id;
    })
    if ($distance == 0) {
        return $this.runExecutor.getSegmentStatusByCode(_.first(sortedArr).itemCode);
    }else{
        _.each(sortedArr,function(ele,index){
            var segLength = $this.runExecutor.getSegmentStatusByCode(ele.itemCode).Length;
          //  console.log("!!!!"+$distance);
            if(!findFlag){
                if (segLength >= $distance) {
                    findFlag = true;
                    currentSegment =  $this.runExecutor.getSegmentStatusByCode(ele.itemCode);
                }else{
                  //  console.log("######################################"+$distance);
                    $distance = $distance - segLength;
                }
            }

        })
    }
    return currentSegment;
    
}

